package com.medicine.hbp.ui;

import java.io.File;

import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.widget.RoundImageView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.medicine.hbp.base.BaseActivity;
import com.medicine.hbp.dialog.PhotographDialog;
import com.medicine.hbp.dialog.PhotographDialog.PhotographDialogListener;
import com.medicine.hbp.http.AppHttpCallBack;
import com.medicine.hbp.http.AppHttps;
import com.medicine.hbp.http.HttpInterface;
import com.medicine.hbp.http.UploadUtil;
import com.medicine.hbp.http.UploadUtil.ImageCallBack;
import com.medicine.hbp.sp.LoginSp;
import com.medicine.hbp.uitl.ChoosePicturesUtils;
import com.medicine.hbp.uitl.CommUtil;
import com.medicine.hbp.uitl.StartIntent;
import com.medicine.hbp.uitl.ToastUtil;
import com.medicine.hbp.R;

/**
 * 用户信息更改页面
 */
public class UserSetActivity extends BaseActivity {
	@BindView(id = R.id.img_userhead, click = true)
	public RoundImageView img_userhead;// 头像
	@BindView(id = R.id.txt_layout_username)
	public TextView txt_layout_username;// 退出登录
	@BindView(id = R.id.txt_layout_userqm)
	public TextView txt_layout_userqm;// 退出登录
	@BindView(id = R.id.btn_exit_login, click = true)
	public Button btn_exit_login;// 退出登录
	@BindView(id = R.id.btn_layout_userqm, click = true)
	public LinearLayout btn_layout_userqm;// 签名点击
	@BindView(id = R.id.btn_layout_username, click = true)
	public LinearLayout btn_layout_username;// 用户名点击

	@Override
	public void setRootView() {
		super.setRootView();
		setContentView(R.layout.activity_user_set);
	}

	@Override
	public void initWidget() {
		super.initWidget();
		url=LoginSp.getUserHead(aty);
		if(!TextUtils.isEmpty(url)){
			bitmap.display(img_userhead, url, 50, 50);
		}
		txt_layout_username.setText(LoginSp.getUserName(aty));
		txt_layout_userqm.setText(LoginSp.getUserSignature(aty));
		initTop();
	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
			case R.id.btn_exit_login:// 退出登录
				httpLogout();
				break;
			case R.id.btn_layout_userqm:// 签名点击
				AlertDialog.Builder builder1=new AlertDialog.Builder(aty);
				builder1.setTitle("请输入个性签名");
				final EditText txt1=new EditText(aty);
				txt1.setMaxLines(100);
				txt1.setTextSize(18);
				builder1.setView(txt1);
				builder1.setNegativeButton("取消", null);
				builder1.setNeutralButton("确定", new AlertDialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						txt_layout_userqm.setText(txt1.getText().toString());
						http();
					}
				});
				builder1.show();
				break;
			case R.id.btn_layout_username:// 用户名点击
				AlertDialog.Builder builder2=new AlertDialog.Builder(aty);
				builder2.setTitle("修改用户名");
				builder2.setMessage("请控制在2-20个字符，仅允许使用汉字、英文、数字、“-”和“_”");
				final EditText txt2=new EditText(aty);
				txt2.setMaxLines(20);
				txt2.setTextSize(18);
				builder2.setView(txt2);
				builder2.setNegativeButton("取消", null);
				builder2.setNeutralButton("确定",new AlertDialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						txt_layout_username.setText(txt2.getText().toString());
						http();
					}
				});
				builder2.show();
				break;
			case R.id.img_userhead:// 用户名点击
				startPhotographDialog();
				break;
			default:
				break;
		}
	}

	private void initTop() {
		TopView topview = (TopView) findViewById(R.id.topview);
		topview.setTitle("账号管理");
		topview.setLeftVisibility(View.GONE);
		topview.setLeftVisibilityExit(View.VISIBLE);
		topview.setRightVisibility(View.INVISIBLE);
		topview.setLeftOnClickExit(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}

	/**
	 * 调用相机拍照选择
	 */
	private void startPhotographDialog() {
		PhotographDialog photographDialog = new PhotographDialog(aty,
				new PhotographDialogListener() {
					@Override
					public void onSelect(int position) {
						if (position == 0) {
							ChoosePicturesUtils.photographic(aty);
						} else {
							ChoosePicturesUtils.pickPhonoImage(aty);
						}
					}

					@Override
					public void onCancel() {
					}
				}, 0);
		photographDialog.showPhotographDialog();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
			case RESULT_OK:
				// 存储卡可用
				if (ChoosePicturesUtils.isHasSdcard()) {
					if (requestCode == ChoosePicturesUtils.REQUEST_CODE_TAKE_PICTURE) {// 拍照返回
						if (!TextUtils.isEmpty(ChoosePicturesUtils.imagePathString)) {
							// imageThrred(ChoosePicturesUtils.imagePathString);
							ChoosePicturesUtils.cropPictures(aty, Uri
									.fromFile(new File(
											ChoosePicturesUtils.imagePathString)));
						}
					} else if (ChoosePicturesUtils.PHOTOZOOM == requestCode) {
						try {
							Uri uri = data.getData();
							if (uri != null) {
								String path = CommUtil.getImageAbsolutePath(aty,
										uri);
								if (!TextUtils.isEmpty(path)) {
									ChoosePicturesUtils.cropPictures(aty,
											Uri.fromFile(new File(path)));
									// imageThrred(path);
								} else {
									ToastUtil.showShort(aty, "从相册中选取照片失败");
								}
							}
						} catch (Exception e) {
							Log.e("ReleaseActivity", e.getMessage());
							e.printStackTrace();
						} finally {
						}
					} else if (ChoosePicturesUtils.REQUEST_CROP_ICON == requestCode) {
						if (!TextUtils.isEmpty(ChoosePicturesUtils.imagePathString)) {
							imageThrred(ChoosePicturesUtils.imagePathString);
						}
					}
				}
				break;
			default:
				break;
		}

	}

	private void imageThrred(final String path) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// httpFile(CommUtil.qrcodeMyBitmap(CommUtil.getimage(path),
				// aty));
				httpFile(path);
			}
		}).start();
	}

	private String url;
	private KJBitmap bitmap = new KJBitmap();

	/**
	 * 文件上传
	 *
	 * @param file
	 */
	private void httpFile(final String file) {
		UploadUtil.uploadFile(new File(file), AppHttps.HTTP_URL+HttpInterface.UPLOAD_FILE, new ImageCallBack() {
			@Override
			public void onSuccess(String urls) {
				url = urls;
				bitmap.display(img_userhead, url, 50, 50);
				http();
			}

			@Override
			public void onFailure(String error) {
				ToastUtil.showShort(aty, error);
			}
		});
	}
	@Override
	protected void onResume() {
		super.onResume();
		if(isexit){
			finish();
		}
	}
	boolean isexit=false;
	/**
	 * 退出登录
	 */
	private void httpLogout() {
		HttpParams params = new HttpParams();
		AppHttps.HttpPost(this, HttpInterface.LOGIN_OUT, params,new AppHttpCallBack<Object>(Object.class, aty) {
			@Override
			public void onSuccess(Object result) {
				LoginSp.exitUser(aty);
				ToastUtil.showShort(aty, "退出系統成功");
				// btn_exit_app.setVisibility(View.GONE);
				isexit=true;
				CommUtil.destroySelfUserTwoActivity();
				StartIntent.startLogin(aty);
				finish();
			}

			@Override
			public void onFailures(int errorCode, String errorMsg) {
				ToastUtil.showShort(aty, errorMsg);
			}
		});

	}
	/**
	 * 用户信息更新接口
	 */
	private void http() {
		HttpParams params = new HttpParams();
		params.put("userHeadImg", url);// 用户头像
		params.put("userSignature", txt_layout_userqm.getText().toString());// 用户签名
		params.put("username", txt_layout_username.getText().toString());// 用户昵称
		params.put("userSex", "");// 性别
		params.put("province", "");// 省份
		params.put("city", "");// 城市
		params.put("county", "");// 区县
		params.put("area", "");// 详细地址

		AppHttps.HttpPost(this, HttpInterface.UPDATE_USER, params,
				new AppHttpCallBack<Object>(Object.class, aty) {
					@Override
					public void onSuccess(Object result) {
						LoginSp.setUserHead(url, aty);
						LoginSp.setUserSignature( txt_layout_userqm.getText().toString(), aty);
						LoginSp.setUserName(txt_layout_username.getText().toString(), aty);
//						finish();
					}

					@Override
					public void onFailures(int errorCode, String errorMsg) {
						ToastUtil.showShort(aty, errorMsg);
					}
				});

	}
}
